﻿using D.B.Data.API.Applications.Command.RoleCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.RoleCommandHandler
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepository<RoleModel> RoleRepository;

        public AddRoleCommandHandler(IBaseRepository<RoleModel> roleRepository)
        {
            RoleRepository = roleRepository;
        }

        Task<APIResult<object>> IRequestHandler<AddRoleCommand, APIResult<object>>.Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {

            APIResult<object> result = new APIResult<object>();    
            var res = RoleRepository.GetAll().Where(s => s.RoleName == request.RoleName&&!s.IsDel);
            if(res.Count()>0)
            {
                result.Code=EnumCode.File;
                result.Msg = "角色名称重复";
                return Task.FromResult(result);
            }


            RoleModel userModel = new RoleModel()
            {
                    RoleName = request.RoleName,
                    CreateTime= DateTime.Now,
                    CreateUserId= request.UserId,
            };
            RoleRepository.Add(userModel);

            result.Code = EnumCode.Ok;
            result.Msg = "添加成功";

            return Task.FromResult(result);
        }
    }
}
